package com.fitz.remote.callback;

import com.fitz.invoke.RpcInvoker;
import com.fitz.remote.client.ConsumerClient;
import com.fitz.remote.model.RpcRequest;
import com.fitz.remote.model.RpcResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author fitz
 * Created by fitz on 2020/5/25
 */
public class RpcResponseCallback implements BaseCallback {

    private static final Logger logger = LoggerFactory.getLogger(RpcResponseCallback.class);

    private final Object lock = new Object();

    private RpcRequest rpcRequest;

    private RpcResponse rpcResponse;

    private ConsumerClient consumerClient;

    private RpcInvoker rpcInvoker;

    public RpcResponseCallback(RpcInvoker rpcInvoker,RpcRequest rpcRequest,ConsumerClient consumerClient) {
        this.rpcInvoker = rpcInvoker;
        this.rpcRequest = rpcRequest;
        this.consumerClient = consumerClient;
        rpcInvoker.setCallback(rpcRequest.getRequestId(),this);
    }

    /**
     * @desc: 回调
     * @author: gousili
     * @Date: 2020/5/28
     * @param: [o]
     * @return: void
     **/
    @Override
    public void call(Object o) {
        this.rpcResponse = (RpcResponse) o;
        synchronized (lock){
            lock.notifyAll();
        }
    }

    public RpcResponse sendRequest(){
        synchronized (lock){
            try {
                consumerClient.sendRequest(rpcRequest);
                lock.wait();
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
        if (rpcResponse != null){
            return rpcResponse;
        }
        return null;
    }

    public void remove(){
        rpcInvoker.removeCallback(rpcRequest.getRequestId());
    }
}
